from machine import Pin, PWM
import time


class IRTransmitter:
    def __init__(self, bit_mark, bit1_space, bit0_space, pin=15, carrier_freq=38000):
        """
        初始化红外发射器
        :param bit_mark: 脉冲宽度，即高电平时间(微秒)
        :param bit1_space: 比特1 低电平持续时间(微秒)
        :param bit0_space: 比特0 低电平续时间(微秒)
        :param pin: 使用的GPIO引脚号,ESP32默认15
        :param carrier_freq: 载波频率(Hz)，默认为38kHz
        """
        self.bit_mark = bit_mark
        self.bit1_space = bit1_space
        self.bit0_space = bit0_space
        self.carrier_freq = carrier_freq

        self.pwm = PWM(Pin(pin))
        self.pwm.freq(carrier_freq)
        self.pwm.duty_u16(0)  # 0-65535，表示0-100%占空比  初始关闭

    def send_bit(self, bit, ratio=0.5):
        """
        发送单个比特
        :param bit: 要发送的比特值(0或1)
        :param ratio: 占空比, 0.5默认50%占空比
        """
        # 发送脉冲(高电平)
        self.pwm.duty_u16(int(65536*ratio))  # 50%占空比
        time.sleep_us(self.bit_mark)
        self.pwm.duty_u16(0)
        if int(bit) == 1:
            time.sleep_us(self.bit1_space)
        else:
            time.sleep_us(self.bit0_space)

    def send_byte(self, byte):
        """发送一个字节，从最高位开始"""
        for i in range(7, -1, -1):
            self.send_bit((byte >> i) & 1)

    def send_segment(self, duration, ratio=0.5):
        self.pwm.duty_u16(int(65536*ratio))  # 50%占空比
        time.sleep_us(duration)
        self.pwm.duty_u16(0)

    def send_data(self, data):
        """
        发送数据序列
        :param data: 要发送的数据字符串(如"110110")或比特列表
        """
        for bit in data:
            self.send_bit(int(bit))
        self.pwm.duty_u16(0)  # 确保最后关闭

    def close(self):
        """释放资源"""
        self.pwm.deinit()
